package com.learn.sb.rabbitmq.service.impl;

import com.learn.sb.rabbitmq.service.RabbitMqService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import pojo.User;

@Service
public class RabbitMqServiceImpl
            implements RabbitTemplate.ConfirmCallback, RabbitMqService {

    @Value("${rabbitmq.queue.msg}")
    private String msgRouting = null;
    @Value("${rabbitmq.queue.user}")
    private String userRouting = null;
    // 注入由Spring Boot自动装配RabbitTemplate
    @Autowired
    private RabbitTemplate rabbitTemplate = null;

    @Override
    public void sendMsg(String msg) {
        System.out.println("发送消息：" + msg);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.convertAndSend(msgRouting, msg);
    }

    @Override
    public void sendUser(User user) {
        System.out.println("发送用户：" + user);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.convertAndSend(userRouting, user);
    }

    // 回调确认方法
    @Override
    public void confirm(@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause) {
        if(ack) {
            System.out.println("消息消费成功");
        } else {
            System.out.println("消息消费失败，原因：" + cause);
        }
    }
}
